import axios from "axios";
import { message } from 'antd';
// import nprogress from 'nprogress'
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});
service.interceptors.request.use(
  function (config: any) {
    // nprogress.start()
    // 在发送请求之前做些什么
    const token = sessionStorage.getItem("token");
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  function (error: any) {
    // 对请求错误做些什么
    // nprogress.done()
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  function (response: any) {
    // 对响应数据做点什么
    // console.log(response)
    if (response.data.code && response.data.code !== '00000') {
      message.error(response.data.msg);
    }
    // nprogress.done()
    return response.data;
  },
  function (error: any) {
    // console.log("error", error);
    const code = error.code;
    switch (code) {
      case "ECONNABORTED":
        message.error("请求超时,请重新尝试");
        break;
      case "ERR_NETWORK":
        message.error("网络开小差~");
        break;
          case 'ERR_BAD_REQUEST':
            message.error(error.message)
          break;
      default:
        message.error(error.message);
    }
    // 对响应错误做点什么
    // ElMessage.error('请求有误，网络开小差')
    // nprogress.done()
    return Promise.reject(error);
  }
);

const get = (url: string, params?: object, responseType?: any) => {
  return service.get(url, { params, responseType }) as any;
};

const post = (url: string, data: object) => {
  return service.post(url, data) as any;
};

export default { get, post };
